package com.platform.framework.util.pub;


import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.platform.framework.vo.info.ExceptionInfo;
import com.platform.framework.vo.pub.ResponseVo;
import com.platform.framework.vo.states.PayGate;
import com.platform.framework.vo.states.PayResult;
import com.platform.framework.vo.transfer.TransportLayer;

import org.apache.log4j.Logger;

public class Validation {
	
	
	private static Logger logger = Logger.getLogger(Validation.class);
	
	

	// Constructors
	public Validation() {
	}


	// Methods
	public static boolean isEmpty(String str) {
		if (str == null || str.trim().equals("")) {
			return true;
		} else {
			return false;
		}
	}
	
	// 验证数字是否为空，或者字符串是否包含字母，不能转化为数字。
	public static boolean isEmptyNum (String str) {
		if (str == null || str.trim().equals("")) {
			return true;
		} 
		
		
		try {
			Double num1 = Double.parseDouble(str);
			if (num1.isNaN() || (num1<0.0001)&&(num1>-0.0001)) {
				return true;
			}
		} catch (Exception e) {
			try {
				Integer num2 = Integer.parseInt(str);
				if (num2 < 1 && num2 > -1) {
					return true ;
				}
			} catch (Exception e2) {
				Pattern p = Pattern.compile(".*(\\w).*");
				Matcher matcher = p.matcher(str);
				
				if (matcher.matches()) {
					return true;
				}
			} 
		} 
		
		return false;
	}
	
	
  
	public static boolean isEmpty(Object str) {
		if(str == null)
			return true;
		if("".equals(String.valueOf(str).trim()) || "null".equalsIgnoreCase(String.valueOf(str).trim()))
			return true;
		return false;
	}  
	public static boolean isEmptyList(List<?> list) {
		if(list==null||list.size()==0){
			return true;
		}else{
			return false;
		}
	} 
//check whether the input is a valid email
	public static boolean isEmail(String email) {
		if (email.indexOf("list:") != -1) email = email.substring(5,email.length());
		if (isEmpty(email)) return false;
		String [] invalid_c = {"~","`","!","#","$","%","^","&","*","(",")","+","=","<",">","?"," ",":",";","\"","{","}","[","]","\\","|","/"};
		for (int i=0; i < email.length()-1; i++) {
			if (email.regionMatches(true,i,"@@",0,2)) return false;
		}
		for (int j=0; j<invalid_c.length; j++) {
			for (int i=0; i < email.length(); i++) {
				if (email.regionMatches(true,i,invalid_c[j],0,1)) return false;
			}
		}
		if ((email.substring(0,1).equals("@")) || (email.substring(email.length()-1,email.length()).equals("@"))) return false;
		StringTokenizer st = new StringTokenizer(email,"@");
		if (st.countTokens() != 2) return false;
		st.nextElement();
		StringTokenizer st1 = new StringTokenizer((String)st.nextElement(),".");
		if (st1.countTokens() < 2) return false;
		return true;
	}  
	/**
	 * ж
	 */
	public static boolean isInteger(String value) {
		try {
			Integer.parseInt(value);
			return true;
		} catch (NumberFormatException e) {
			return false;
		}
	}

	/**
	 * ж
	 */
	public static boolean isDouble(String value) {
		try {
			Double.parseDouble(value);
				return true;

		} catch (NumberFormatException e) {
			return false;
		}
	}

	/**
	 * ж
	 */
	public static boolean isNumber(String value) {
		return isDouble(value);
	}
	
	public static boolean isDate(String str) {
		boolean flag = true;
		try {
			DateFormat.getDateInstance().parse(str);
		} catch (Exception e) {
			flag = false;
			// TODO: handle exception
		}
		return flag;
	}
	
	public static boolean isTimestamp(String str){
		boolean flag = true;
		try {
	          SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
	          java.text.ParsePosition pos = new java.text.ParsePosition(0);
	          java.util.Date tempDate = formatDate.parse(str,pos);
	          new Timestamp(tempDate.getTime());
	  	} catch(Exception ex) {
	  		flag = false;
	  	}
		return flag;
	}
	
	public static boolean isBoolean(String str){
		boolean flag = true;
		try {
			Boolean.parseBoolean(str);
	  	} catch(Exception ex) {
	  		flag = false;
	  	}
		return flag;
	}
	
	public static boolean isEmptyJson (String str) {
		if (str == null || str.trim().equals("")) {
			return true;
		}
		
		if (str.trim().equals("[]")) {
			return true;
		}
		
		return false;
	}
	
	
	
	public static ResponseVo validationTrans (TransportLayer transportLayer) {
		
		if (Validation.isEmpty(transportLayer.getPayType())) {
			logger.error("[tradelog:"+transportLayer.getOrderNo()+"] payType is null in transportLayer!payType输入不能为空！");
			return new ResponseVo(PayResult.ERROR, null, ExceptionInfo.VALIDATE_PARAMS_FAIL + ":payType.", null);
		}
		
		if (Validation.isEmpty(transportLayer.getPayGate())) {
			logger.error("[tradelog:"+transportLayer.getOrderNo()+"] payGate is null in transportLayer!payGate输入不能为空！");
			return new ResponseVo(PayResult.ERROR, null, ExceptionInfo.VALIDATE_PARAMS_FAIL + ":payGate.", null);
		}
		
		if (Validation.isEmpty(transportLayer.getOrderNo())) {
			logger.error("[tradelog:"+transportLayer.getOrderNo()+"] outTradeNo is null in transportLayer!订单号输入不能为空！");
			return new ResponseVo(PayResult.ERROR, null, ExceptionInfo.VALIDATE_PARAMS_FAIL + ":outTradeNo.", null);
		}
		
		if (Validation.isEmpty(transportLayer.getLoginName())) {
			logger.error("[tradelog:"+transportLayer.getOrderNo()+"] loginName is null in transportLayer!登录名输入不能为空！");
			return new ResponseVo(PayResult.ERROR, null, ExceptionInfo.VALIDATE_PARAMS_FAIL + ":loginName.", null);
		}
		
		// 扫码、条码支付验参
		if (!Validation.isEmpty(transportLayer.getPayGate()) && (transportLayer.getPayGate().equals(PayGate.BAR_CODE_PAY) || transportLayer.getPayGate().equals(PayGate.QRCODE_PAY))) {
			
			if (transportLayer.getPayGate().equals(PayGate.BAR_CODE_PAY) && Validation.isEmpty(transportLayer.getAuthCode()) ) {
				logger.error("[tradelog:"+transportLayer.getOrderNo()+"] authCode is null in transportLayer!条形码输入不能为空！");
				return new ResponseVo(PayResult.ERROR, null, ExceptionInfo.VALIDATE_PARAMS_FAIL + ":authCode.", null);
			}
			
			if (Validation.isEmpty(transportLayer.getBody())) {
				logger.error("[tradelog:"+transportLayer.getOrderNo()+"] body is null in transportLayer!body输入不能为空！");
				return new ResponseVo(PayResult.ERROR, null, ExceptionInfo.VALIDATE_PARAMS_FAIL + ":body.", null);
			}
			
			if (PayGate.QRCODE_PAY.equals(transportLayer.getPayGate()) && Validation.isEmpty(transportLayer.getNotifyUrl())) {
				logger.error("[tradelog:"+transportLayer.getOrderNo()+"] notifyUrl is null in transportLayer!notifyUrl输入不能为空！");
				return new ResponseVo(PayResult.ERROR, null, ExceptionInfo.VALIDATE_PARAMS_FAIL + ":notifyUrl.", null);
			}
			
			if (Validation.isEmptyNum(transportLayer.getTotalAmount())) {
				logger.error("[tradelog:"+transportLayer.getOrderNo()+"] totalAmount is null in transportLayer!总金额输入不能为空！");
				return new ResponseVo(PayResult.ERROR, null, ExceptionInfo.VALIDATE_PARAMS_FAIL + ":totalAmount.", null);
			}
		}
		
		// 退款验参
		if (!Validation.isEmpty(transportLayer.getPayGate()) && transportLayer.getPayGate().equals(PayGate.TRADE_REFUND)) {
			if (Validation.isEmpty(transportLayer.getRefundAmount())) {
				logger.error("[tradelog:"+transportLayer.getOrderNo()+"] 退款金额不能为空！！");
				return new ResponseVo(PayResult.ERROR, null, ExceptionInfo.VALIDATE_PARAMS_FAIL + ":refundAmount.", null);
			}
			if (Validation.isEmpty(transportLayer.getRefundReason())) {
				logger.error("[tradelog:"+transportLayer.getOrderNo()+"] 退款原因不能为空！！");
				return new ResponseVo(PayResult.ERROR, null, ExceptionInfo.VALIDATE_PARAMS_FAIL + ":refundReason.", null);
			}
		}
		
		return null;
		
	}
	
	
}
